package classfile

import (
	"gitee.com/microwww/jvm-go/jvm/tool"
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
)

const (
	Separator     = string(os.PathSeparator)     // windows `\`  linux `/`
	ListSeparator = string(os.PathListSeparator) // windows `;`  linux `:`
)

func init() {
	// fmt.Println("loading classfile/classpath.go")
}

func LookupClass(path *tool.Path, class string) ([]byte, Entity, error) {
	{
		cp := path.BootClasspath
		com := dirJars(cp)
		bys, et, e := com.Read(class)
		if e == nil {
			return bys, et, e
		}
	}
	{
		cp := path.ExtendClasspath
		com := dirJars(cp)
		bys, et, e := com.Read(class)
		if e == nil {
			return bys, et, e
		}
	}

	for _, s := range path.UserClasspath {
		bys, et, e := ParseEntity(s).Read(class)
		if e == nil {
			return bys, et, e
		}
	}

	return nil, nil, errors.New("Not find class : " + class)
}

func dirJars(dir string) CompositeEntity {
	fs, _ := ioutil.ReadDir(dir)
	com := make(CompositeEntity, 0, 20)
	for _, f := range fs {
		if !f.IsDir() {
			if filepath.Ext(f.Name()) == ".jar" {
				com = append(com, newZipEntity(filepath.Join(dir, f.Name())))
			}
		}
	}
	return com
}
